import { create, update, remove, query } from '../../../../framework/service/index';
import { ToastTips } from '../../../../common/toastTips/tosat';

export default {

  namespace: 'enterpriseInformation',

  state: {
    customers: {},
    partTimeList:[],
  },

  subscriptions: {
    setup({ dispatch, history }) {
      history.listen(location => {
        if(location.pathname === '/enterprise-information') {
          const id = location.query.id;
          dispatch({
            type: 'query',
            payload: {
              id
            }
          });

          dispatch({
            type: 'getCMPartTimes',
            payload: {
              id
            }
          })
        }
      })
    },
  },

  effects: {
    *query({ payload }, { call, put }) {  // eslint-disable-line
      // console.log('id搜商家',payload.id);
      const { code, data, message } = yield call(query, `/api/pub/customers/${payload.id}`, {});
      console.log('商家详情', JSON.stringify(data));
      if (code === 200 && data) {
        yield put({
          type: 'querySuccess',
          payload: {
            customers: data
          }
        })
      }else{
        console.log('获取商家详情失败');
      }
    },

    //获取当前商家发布的兼职列表
    *getCMPartTimes({ payload }, { call, put }) {
      // console.log('id搜商家',payload.id);
      const { id } = payload;
      const { code, data, message } = yield call(query, `/api/pub/jobs/owner/${id}`, {});
      if (code === 200 && data) {
        // console.log('商家发布的兼职 data', JSON.stringify(data));
        let newList = [];
        data.map((item, index) => {
          if(item.status == 'APPLYING' || item.status == 'CLOSE'){
            newList.push(item);
          }
        });
        yield put({
          type: 'querySuccess',
          payload: {
            partTimeList: newList
          }
        })
      }else{
        console.log('获取当前商家发布兼职失败');
      }
    },

    //关注商家
    *postFollow({ payload }, { call, put, select }) {
      // console.log('id搜商家',payload.id);
      const { id } = payload;

      const { code, data, message } = yield call(create, `/api/customers/${id}/favors`, {});
        // console.log('商家发布的兼职 code', JSON.stringify(code));
        // console.log('商家发布的兼职 data', JSON.stringify(data));
        // console.log('商家发布的兼职 message', JSON.stringify(message));
      if (code === 200) {

        const customers = yield select(({ enterpriseInformation }) => enterpriseInformation.customers);
        customers.favors = data;
        yield put({
          type:'querySuccess',
          payload:{
            customers
          }
        })
        if(data == 0){
          ToastTips('取消关注', 2000, null);
        }else if(data == 1){
          ToastTips('关注成功', 2000, null);
        }

      }else{
        console.log('关注失败');
        ToastTips('关注失败', 2000, null);
      }
    },
  },

  reducers: {
    querySuccess(state, action) {
      return { ...state, ...action.payload };
    },
  }

};
